package com.xinqi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.bean.Goods;
import com.xinqi.common.R;
import com.xinqi.mapper.GoodsMapper;
import com.xinqi.service.IGoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xin麒
 * @date 2023/2/17 15:31
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
    @Override
    @Transactional
    public R buyOneGoods(Long goodsId) {
        Goods goods = getById(goodsId);

        if (goods == null || goods.getStock() <= 0) return R.fail("has not any stock");//step 1

        boolean success = update()
                .setSql("stock = stock - 1")
                .eq("id", goodsId)
                .gt("stock", goods.getStock() / 3)//这里比较前后的数据是否相等，相等就可以修改库存
                .update();//step 2

        if (!success) {
            return R.fail("has not any stock");
        }
        return R.success("buy one success");
    }

/*    @Override
    public R buyOneGoods(Long goodsId) {
        Goods goods = getById(goodsId);

        if (goods == null || goods.getStock() <= 0) return R.fail("has not any stock");//step 1

        boolean success = update()
                .setSql("stock = stock - 1")
                .eq("id", goodsId)
                .gt("stock", 0)//这里比较前后的数据是否相等，相等就可以修改库存
                .update();//step 2

        if (!success) {
            return R.fail("has not any stock");
        }
        return R.success("buy one success");
    }*/

/*    @Override
    public R buyOneGoods(Long goodsId) {
        Goods goods = getById(goodsId);

        if (goods == null || goods.getStock() <= 0) return R.fail("has not any stock");//step 1

        boolean success = update()
                .setSql("stock = stock - 1")
                .eq("id", goodsId)
                .eq("stock", goods.getStock())//这里比较前后的数据是否相等，相等就可以修改库存
                .update();//step 2

        if (!success) {
            return R.fail("has not any stock");
        }
        return R.success("buy one success");
    }*/

/*    @Override
    public R buyOneGoods(Long goodsId) {
        Goods goods = getById(goodsId);

        if (goods.getStock() <= 0) return R.fail("has not any stocks");//第一步

        boolean success = update()//第二步
                .setSql("stock = stock - 1")
                .update();

        return R.success("buy one successfully");
    }*/

}
